package cn.trkj.server.servlet;

import cn.trkj.server.dto.FileDTO;
import cn.trkj.server.service.FileService;
import cn.trkj.server.service.impl.FileServiceImpl;
import cn.trkj.server.util.DateUtils;
import cn.trkj.server.util.FileUtil;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import org.eclipse.jetty.server.Request;

import javax.servlet.MultipartConfigElement;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.*;
import java.sql.Timestamp;
import java.util.Collection;
import java.util.UUID;

/**
 * @author admin
 * @date 2021/2/20 3:30 下午
 */
@WebServlet(name = "FileUploadServlet", urlPatterns = "/file/upload")
@MultipartConfig
public class FileUploadServlet extends HttpServlet {

    private static final MultipartConfigElement MULTI_PART_CONFIG = new MultipartConfigElement("upload");


    /**
     * 注入FileService
     */
    FileService fileService = new FileServiceImpl();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) {
        try {
            System.out.println("========doPost==========");
            request.setCharacterEncoding("utf-8");
            response.setCharacterEncoding("utf-8");
            response.setContentType("text/html;charset=utf-8");
            String contentType = request.getContentType();
            String dateUtil = DateUtils.addDay1(new java.util.Date(), -1);
            String dirPath = MULTI_PART_CONFIG.getLocation() + File.separator + dateUtil;
            File dirFile = new File(dirPath);
            if (!dirFile.exists()) {
                dirFile.mkdirs();
            }
            //存储路径
            if (contentType != null && contentType.startsWith("multipart/")) {
                request.setAttribute(Request.__MULTIPART_CONFIG_ELEMENT, MULTI_PART_CONFIG);
                //获取上传的文件集合
                Collection<Part> parts = request.getParts();
                //上传单个文件
                if (parts.size() == 1) {
                    Part part = request.getPart("file");
                    // 原文件名
                    String originName = getFileName(part);
                    // 文件后缀
                    String type = originName.substring(originName.lastIndexOf("."));
                    if (".mp4".equals(type)) {
                        return;
                    }
                    // 新的文件名：UUID
                    String uuid = UUID.randomUUID().toString();
                    // 存储位置
                    String position = dirPath + File.separator + uuid + type;
                    // 将文件存储到本地
                    InputStream is = part.getInputStream();
                    FileOutputStream fos = new FileOutputStream(position);
                    try {
                        byte[] bytes = new byte[1024];
                        int length = 0;
                        while ((length = is.read(bytes)) != -1) {
                            fos.write(bytes, 0, length);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        fos.close();
                        is.close();
                    }

                    // 存储信息到数据库
                    FileDTO fileDTO = new FileDTO();
                    fileDTO.setId(uuid);
                    fileDTO.setName(originName);
                    String img = "";
                    fileDTO.setType(type);
                    if (".jpg".equals(type)) {
                        fileDTO.setStatus("1");
                        img = originName.split("_img")[0];
                    } else if (".txt".equals(type)) {
                        fileDTO.setStatus("2");
                        img = originName.split("_desc")[0];
                        File file = new File(position);
                        String s = txt2String(file);
                        StringToJson(s, fileDTO);
                    } else {
                        return;
                    }
                    fileDTO.setJqName(img);
                    fileDTO.setSize(FileUtil.parseSize(part.getSize()));
                    String dateUtil1 = DateUtils.addDay(new java.util.Date(), -1);
                    fileDTO.setTime(dateUtil1);
                    fileDTO.setLocation(position);
                    try {
                        fileService.insert(fileDTO);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private String getFileName(Part part) {
        String head = part.getHeader("Content-Disposition");
        String fileName = head.substring(head.indexOf("filename=\"") + 10, head.lastIndexOf("\""));
        return fileName;
    }

    /**
     * 读取txt文件的内容
     *
     * @param file 想要读取的文件对象
     * @return 返回文件内容
     */
    public static String txt2String(File file) {
        StringBuilder result = new StringBuilder();
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), "gbk"));
            String s = null;
            while ((s = br.readLine()) != null) {
                result.append(System.lineSeparator() + s);
            }
            br.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result.toString();
    }


    public void StringToJson(String jsonString, FileDTO fileDTO) {
        Gson gson = new Gson();
        try {
            JsonObject jsonObject = gson.fromJson(jsonString, JsonObject.class);
            fileDTO.setCarcolor(jsonObject.get("carcolor").getAsString());
            fileDTO.setCartype(jsonObject.get("cartype").getAsString());
            fileDTO.setColor(jsonObject.get("color").getAsString());
            fileDTO.setConfidencelevel(jsonObject.get("confidencelevel").getAsString());
            fileDTO.setFogpos(jsonObject.get("fogpos").getAsString());
            fileDTO.setIdroad(jsonObject.get("idroad").getAsString());
            fileDTO.setLicense(jsonObject.get("license").getAsString());
            fileDTO.setRingelmann(jsonObject.get("ringelmann").getAsString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
